"ui";
engines.all().map((ScriptEngine) => {
  if (engines.myEngine().toString() !== ScriptEngine.toString()) {
    ScriptEngine.forceStop();
  }
});
let yashuUtil = require("./yashu-util.js");
let serverService = require("./server-service.js");
let FloatingWindow = require("./floating-window.js");
let config = require("./config.js");
console.log("main 工作路径: " + files.cwd());

ui.layout(
  <vertical>
    <text textColor="#ff0000" textSize="30sp">
      1.1.23
    </text>
    <horizontal layout_width="match_parent" gravity="left" margin="8">
      <text text="无障碍权限" textStyle="bold" textSize="26sp" />
      <Switch id="无障碍" layout_width="match_parent" />
    </horizontal>
    <horizontal layout_width="match_parent" gravity="left" margin="8">
      <text text="悬浮窗权限" textStyle="bold" textSize="26sp" />
      <Switch id="悬浮窗" layout_width="match_parent" />
    </horizontal>
    <horizontal layout_width="match_parent" gravity="left" margin="8">
      <text text="显示悬浮窗" textStyle="bold" textSize="26sp" />
      <Switch id="显示悬浮窗" layout_width="match_parent" />
    </horizontal>
    <button id="启动脚本">启动脚本</button>
    <button id="停止脚本">停止脚本</button>
    <button id="更新脚本">更新脚本</button>
    <button id="日志" marginTop="8" bg="#339af0" textColor="#ffffff">
      日志
    </button>
    <globalconsole id="globalconsole" w="*" h="*" />
  </vertical>
);
ui.更新脚本.click(function () {
  engines.execScriptFile(config.destination + "entrance.js");
});
ui.日志.click(function () {
  app.startActivity("console");
});
let floatingWindow = null;
ui.显示悬浮窗.checked = true;
ui.显示悬浮窗.on("check", function (checked) {
  if (checked) {
    if (!$floaty.checkPermission()) {
      // 没有悬浮窗权限，提示用户并跳转请求
      toastLog("本脚本需要悬浮窗权限来显示悬浮窗，请在随后的界面中允许并重新运行本脚本。");
      $floaty.requestPermission();
    } else {
      floatingWindow = floatingWindow || new FloatingWindow();
      floatingWindow.show();
    }
  } else {
    floatingWindow && floatingWindow.hide();
  }
});
let queue = [];
function advertise() {
  let 限制群名列表 = config.限制群名列表;
  let groupIds = config.groupIds;
  let advertising = config.advertising;
  let clocksWithFlag = config.clocks.map((clock) => {
    return { hour: clock, hasPushed: false };
  });
  setInterval(function () {
    let nowHour = new Date().getHours();
    log("nowHour: " + nowHour);
    let reset = false;
    if (nowHour == 2 && !reset) {
      clocksWithFlag.map((clock) => {
        clock.hasPushed = false;
      });
      reset = true;
    }

    var len = clocksWithFlag.length;
    for (var i = 0; i < len; i++) {
      var clock = clocksWithFlag[i];
      if (clock.hour == nowHour && !clock.hasPushed) {
        /* -------------------------------------------------------------------------- */
        var groupIdsLen = groupIds.length;
        for (var j = 0; j < groupIdsLen; j++) {
          let groupId = groupIds[j];
          let groupName = 限制群名列表[j];
          let message = advertising;
          queue.push({
            groupId: groupId,
            groupName: groupName,
            message: message,
          });
        }
        /* -------------------------------------------------------------------------- */
        clock.hasPushed = true;
      }
    }
  }, config.advertisingIntervalCheckTime);
}
threads.start(function () {
  // 定时发广告
  advertise();
});
floatingWindow = new FloatingWindow(queue);
ui.post(function () {
  log("--------> ui.post: " + "floatingWindow: show");
  floatingWindow.show();
}, 500);
ui.悬浮窗.checked = $floaty.checkPermission();
ui.悬浮窗.on("check", function (checked) {
  if (checked) {
    if (!$floaty.checkPermission()) {
      // 没有悬浮窗权限，提示用户并跳转请求
      toastLog("本脚本需要悬浮窗权限来显示悬浮窗，请在随后的界面中允许并重新运行本脚本。");
      $floaty.requestPermission();
    }
  }
});
ui.无障碍.checked = auto.service ? true : false;
ui.无障碍.on("check", function (isChecked) {
  if (isChecked && auto.service == null) {
    toastLog("请开启无障碍权限");
    setTimeout(function () {
      app.startActivity({
        action: "android.settings.ACCESSIBILITY_SETTINGS", //跳转无障碍intent
      });
      return;
    }, 1000);
  } else {
    auto.service && auto.service.disableSelf(); //关闭无障碍
  }
});
ui.emitter.on("resume", () => {
  log("resume");
  ui.post(() => {
    if (auto.service == null) {
      ui.无障碍.checked = false;
    } else {
      ui.无障碍.checked = true;
    }
  }, 500);
});
ui.post(function () {
  if (auto.service != null) {
    ui.启动脚本.performClick();
  } else {
    // app.startActivity({
    //   action: "android.settings.ACCESSIBILITY_SETTINGS", //跳转无障碍intent
    // });
    toastLog("请开启无障碍权限");
  }
}, 1000);
ui.启动脚本.click(启动脚本);
ui.停止脚本.click(停止脚本);
/* -------------------------------------------------------------------------- */
let nodejsExecution = null;
let botThreadId = null;
if (botThreadId) {
  botThreadId.interrupt();
}
$events.on("reply", (data) => {
  console.log("rhino 收到回复: " + JSON.stringify(data));
  queue.push(data);
});
function 停止脚本() {
  nodejsExecution && nodejsExecution.engine.forceStop();
}
function 启动脚本() {
  // 启动Node.js脚本
  // eslint-disable-next-line no-unused-vars
  log("启动脚本: 工作路径: " + files.cwd());
  // return true;
  nodejsExecution = $engines.execScriptFile("./server.js", {
    arguments: {
      serverEngineId: $engines.myEngine().id,
    },
  });
  threads.start(function () {
    //传递第三个参数为true以循环播放音乐
    let audioPath = "./no-sound.mp3";
    media.playMusic(audioPath, 1, true);
  });

  botThreadId = threads.start(function () {
    // eslint-disable-next-line no-constant-condition
    while (true) {
      sleep(1000);
      if (queue.length > 0) {
        let data = queue.shift();
        console.log("rhino 处理回复: " + JSON.stringify(data));
        try {
          serverService.sendGroupMsg(data, floatingWindow);
        } catch (e) {
          log(e && e.stack);
        }
      }
    }
  });
}
